using B.S.XZYData.Api.Read.Application.Command.ZSH;
using B.S.XZYData.Api.Read.DTO;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.ZSH
{
	/// <summary>
	/// 不良品项分页查询处理器
	/// </summary>
	public class GetDefectivePageHandler : IRequestHandler<GetDefectivePageCommand, ApiPageing<DefectiveDto>>
	{
		private readonly IBaseRepository<Defective> _repo;
		private readonly IBaseRepository<AccountModel> _accountRepo;

		public GetDefectivePageHandler(IBaseRepository<Defective> repo, IBaseRepository<AccountModel> accountRepo)
		{
			_repo = repo;
			_accountRepo = accountRepo;
		}

		/// <summary>
		/// 处理分页查询，支持按不良品项编号、名称的模糊查询
		/// </summary>
		public async Task<ApiPageing<DefectiveDto>> Handle(GetDefectivePageCommand request, CancellationToken cancellationToken)
		{
			var res = new ApiPageing<DefectiveDto>();

			// 基础查询：排除已删除
			var query = _repo.GetAll().Where(x => !x.IsDeleted);
			// 模糊筛选：不良品项编号
			if (!string.IsNullOrWhiteSpace(request.DefectiveCode))
				query = query.Where(x => x.DefectiveCode.Contains(request.DefectiveCode));
			// 模糊筛选：不良品项名称
			if (!string.IsNullOrWhiteSpace(request.DefectiveName))
				query = query.Where(x => x.DefectiveName.Contains(request.DefectiveName));

			res.TotaCount = query.Count();
			// 修复分页计算：避免除零和负数
			res.TotaPage = res.TotaCount > 0 ? (int)Math.Ceiling((double)res.TotaCount / request.Size) : 0;

			var list = query
				.OrderByDescending(x => x.CreateTime)
				.Skip((request.Index - 1) * request.Size)
				.Take(request.Size)
				.ToList();

			// 获取所有相关的用户ID（转换为long类型以匹配AccountModel.Id）
			var creatorIds = list.Select(x => (long)x.CreatorId).Distinct().ToList();
			var modifierIds = list.Where(x => x.ModifierId.HasValue).Select(x => (long)x.ModifierId.Value).Distinct().ToList();
			var allUserIds = creatorIds.Concat(modifierIds).Distinct().ToList();

			// 批量查询用户信息
			var users = _accountRepo.GetAll().Where(u => allUserIds.Contains(u.Id)).ToList();

			// 构建DTO列表，包含用户名称
			var dtoList = list.Select(x => new DefectiveDto
			{
				Id = x.Id,
				DefectiveCode = x.DefectiveCode,
				DefectiveName = x.DefectiveName,
				AttachmentPath = x.AttachmentPath,
				ImagePath = x.ImagePath,
				CreateTime = x.CreateTime,
				CreatorId = x.CreatorId,
				ModifierId = x.ModifierId,
				ModifyTime = x.ModifyTime,
				CreatorName = users.FirstOrDefault(u => u.Id == (long)x.CreatorId)?.RealName ?? string.Empty,
				ModifierName = x.ModifierId.HasValue ? users.FirstOrDefault(u => u.Id == (long)x.ModifierId.Value)?.RealName ?? string.Empty : string.Empty
			}).ToList();

			res.PageData = dtoList;
			res.Code = ApiEnum.Success;
			res.Msg = "查询成功";
			return await Task.FromResult(res);
		}
	}
}


